import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sprintf/sprintf.dart';
import 'CheckDialog.dart';
import 'Device.dart';
import 'InputDialog.dart';
import 'LoginPage.dart';

import 'model/data.dart';

class DetailPage extends StatefulWidget {
  final Device device;

  DetailPage(this.device);

  @override
  State<DetailPage> createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  String _name = "";
  String _phone = "";
  String _date = "";
  int _days = 0;
  String _startTime = "";
  String _endTime = "";

  @override
  Widget build(BuildContext context) {
    double price = double.parse(widget.device.price) / 100.0;

    return Scaffold(
      body: SafeArea(
          child: ListView(
            children: [
              Container(
                width: Get.width,
                height: Get.width * 0.8,
                color: Colors.white,
                alignment: Alignment.center,
                child: ExtendedImage.network(
                  "http://cdn.wfhero.online/device/${widget.device.pic}.jpg",
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 15),
                child: Row(
                  children: [
                    _tagWidget("高端设备"),
                    _tagWidget("尽情畅玩"),
                    _tagWidget("品牌保障")
                  ],
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              Container(
                margin: const EdgeInsets.symmetric(horizontal: 15),
                padding: const EdgeInsets.all(15),
                decoration: BoxDecoration(
                    color: Colors.white, borderRadius: BorderRadius.circular(15)),
                child: Column(
                  children: [
                    Text(
                      widget.device.name,
                      style: const TextStyle(
                          color: Colors.black, fontWeight: FontWeight.w600),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    Container(
                      alignment: Alignment.centerRight,
                      child: Text(
                        sprintf("￥%.2f/天", [price]),
                        style: const TextStyle(color: Colors.red, fontSize: 20),
                      ),
                    )
                  ],
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              _infoWidget(),
              _introWidget(),
              const SizedBox(
                height: 20,
              ),
              Column(
                children: [
                  InkWell(
                    onTap: () async {
                      SharedPreferences preference =
                      await SharedPreferences.getInstance();
                      bool login = preference.getBool("login") ?? false;
                      if (!login) {
                        showLoginPage(context);
                        return;
                      }

                      if (_name.isEmpty) {
                        EasyLoading.showInfo("请完善联系人姓名");
                        return;
                      }
                      if (_phone.isEmpty) {
                        EasyLoading.showInfo("请完善联系人手机号");
                        return;
                      }

                      if (_date.isEmpty) {
                        EasyLoading.showInfo("请完善租用日期");
                        return;
                      }

                      showCheckDialog(context, {
                        "name": _name,
                        "phone": _phone,
                        "start": _startTime,
                        "end": _endTime,
                        "days": _days.toString()
                      }).then((value) {
                        if (value != null) {
                          var box = Hive.box('box');

                          List<Order> _list = List<Order>.from(
                              box.get('order', defaultValue: <dynamic>[]));
                          Order order = Order(
                              name: widget.device.name,
                              pic: widget.device.pic,
                              price: widget.device.price,
                              startTime: _startTime,
                              endTime: _endTime);
                          _list.insert(0, order);
                          box.put("order", _list);

                          List<Msg> msgs = List<Msg>.from(
                              box.get('msg', defaultValue: <dynamic>[]));
                          msgs.insert(0, Msg(content: "${widget.device.name} 已提交申请，待审核", time: DateTime.now().millisecondsSinceEpoch));
                          box.put("msg", msgs);

                          Navigator.of(context).pop();
                        }
                      });
                    },
                    child: Container(
                      width: 200,
                      height: 50,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          gradient: const LinearGradient(
                              colors: [Color(0xFFFF8343), Color(0xFFFF6C72)])),
                      child: const Text(
                        "开始租用",
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w600,
                            fontSize: 18),
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(
                height: 30,
              )
            ],
          )),
    );
  }

  final String _desc =
      "1.使用前，请仔细查看设备外观和性能是否正常，如遇异常请及时联系我们进行更换\n\n2.请正常使用设备，禁止恶意损坏\n\n3.使用结束后，请尽快归还，避免违约\n\n4.寄出设备无需你承担运费，但是寄回设备需要你承担运费";

  Widget _introWidget() {
    return Column(
      children: [
        const SizedBox(
          height: 10,
        ),
        Container(
          width: 100,
          height: 30,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(15),
              gradient: LinearGradient(colors: [
                const Color(0xFFFF8343).withOpacity(0.7),
                const Color(0xFFFF6C72).withOpacity(0.7)
              ])),
          child: const Text(
            "租用说明",
            style: TextStyle(color: Colors.white),
          ),
        ),
        const SizedBox(
          height: 10,
        ),
        Container(
          padding: const EdgeInsets.all(15),
          margin: const EdgeInsets.symmetric(horizontal: 15),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(15)),
          child: Text(_desc),
        ),
      ],
    );
  }

  Widget _infoWidget() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 15),
      padding: const EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(15)),
      child: Column(
        children: [
          SizedBox(
            height: 40,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text("押金"),
                Container(
                  width: 60,
                  height: 20,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: const Color(0xFFFF8343).withOpacity(0.1),
                      border: Border.all(color: const Color(0xFFFF8343)),
                      borderRadius: BorderRadius.circular(10)),
                  child: const Text(
                    "免押金",
                    style: TextStyle(fontSize: 12, color: Color(0xFFFF8343)),
                  ),
                ),
              ],
            ),
          ),
          const Divider(),
          InkWell(
            onTap: () {
              showInputDialog(Get.context!, 0, _name).then((value) {
                if (value != null) {
                  setState(() {
                    _name = value;
                  });
                }
              });
            },
            child: SizedBox(
              height: 40,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text("联系人姓名"),
                  const Spacer(),
                  Text(_name),
                  const Icon(Icons.arrow_right)
                ],
              ),
            ),
          ),
          const Divider(),
          InkWell(
            onTap: () {
              showInputDialog(Get.context!, 1, _phone).then((value) {
                if (value != null) {
                  setState(() {
                    _phone = value;
                  });
                }
              });
            },
            child: SizedBox(
              height: 40,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text("联系人手机号"),
                  const Spacer(),
                  Text(_phone),
                  const Icon(Icons.arrow_right)
                ],
              ),
            ),
          ),
          const Divider(),
          InkWell(
            onTap: _showDate,
            child: SizedBox(
              height: 40,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text("租用日期"),
                  const Spacer(),
                  Text(_date),
                  const Icon(Icons.arrow_right)
                ],
              ),
            ),
          ),
          const Divider(),
        ],
      ),
    );
  }

  void _showDate() {
    showCalendarDatePicker2Dialog(
      context: context,
      config: CalendarDatePicker2WithActionButtonsConfig(
        firstDayOfWeek: 1,
        calendarType: CalendarDatePicker2Type.range,
        selectedDayTextStyle:
        const TextStyle(color: Colors.white, fontWeight: FontWeight.w700),
        selectedDayHighlightColor: Colors.redAccent,
        centerAlignModePicker: true,
        customModePickerIcon: const SizedBox(),
        firstDate: DateTime.now(),
      ),
      dialogSize: const Size(325, 400),
      borderRadius: BorderRadius.circular(15),
    ).then((value) {
      if (value != null) {
        if (value.length != 2) {
          EasyLoading.showInfo("请选择正确的日期区间");
          _showDate();
        } else {
          DateTime? firstDate = value.first;
          DateTime? lastDate = value.last;
          if (firstDate == null || lastDate == null) {
            return;
          }

          _startTime = sprintf(
              "${firstDate.year}/%02d/%02d", [firstDate.month, firstDate.day]);
          _endTime = sprintf(
              "${lastDate.year}/%02d/%02d", [lastDate.month, lastDate.day]);

          setState(() {
            _date = "$_startTime ~ $_endTime";
          });

          _days = lastDate.difference(firstDate).inDays;
        }
      }
    });
  }

  Widget _tagWidget(String title) {
    return Row(
      children: [
        Image.asset(
          "images/duihao.png",
          width: 20,
        ),
        const SizedBox(
          width: 2,
        ),
        Text(
          title,
          style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
        ),
        const SizedBox(
          width: 10,
        ),
      ],
    );
  }
}
